<template>
  <div class="top">
    <div>
      您好！{{ ruleForm.userName
      }}<span class="out" @click="outlogin()" v-show="store.state.user.user_id"
        >退出登录</span
      >
    </div>
    <div class="top_right">
      <span v-show="store.state.user.user_id">
        <span class="top_item" @click="$router.push('/shoppingCart')"
          >购物车</span
        >
        <span class="top_item" @click="$router.push('/order')"> 我的订单</span>
        <span class="top_item" @click="$router.push('/starpage')">
          我的收藏</span
        >
      </span>

      <el-button
        type="primary"
        class="ml-1"
        @click="open(0)"
        v-show="!store.state.user.user_id"
        >登录</el-button
      >
      <el-button
        type="primary"
        class="ml-1"
        @click="open(1)"
        v-show="!store.state.user.user_id"
        >注册</el-button
      >
    </div>
  </div>
  <el-dialog
    v-model="centerDialogVisible"
    :title="flag == 0 ? '登录' : '注册'"
    width="40%"
    align-center
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="40px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确认</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { computed, reactive, ref, inject, onMounted } from "vue";
import { useStore } from "vuex";
import { loginApi, registerApi } from "../api/goods";
import { ElMessage } from "element-plus";
const centerDialogVisible = ref(false);
const store = useStore();
const refresh = inject("reload");

let tip = ref();
const flag = ref(0);

const ruleForm = reactive(
  JSON.parse(localStorage.getItem("user")) || {
    user_id: "",
    userName: "",
  }
);

const ruleFormRef = ref();

const checkUserName = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入账号！"));
  } else {
    let reg = /^[a-zA-Z][a-zA-Z0-9_]{4,17}$/gi;

    let namejudge = reg.test(value);

    if (!namejudge) {
      return callback(
        new Error("账号必须以字母开头，且长度在5-16个字符之间！")
      );
    } else {
      callback();
    }
  }
};
const checkPassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入密码！"));
  } else {
    let reg2 = /^[a-zA-Z][a-zA-Z0-9_]{5,19}$/gi;
    let passwordjudge = reg2.test(value);

    if (!passwordjudge) {
      return callback(
        new Error("密码必须以字母开头，且长度在6-17个字符之间！")
      );
    } else {
      callback();
    }
  }
};

const rules = reactive({
  userName: [{ validator: checkUserName, trigger: "blur" }],
  password: [{ validator: checkPassword, trigger: "blur" }],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      if (flag.value == 0) {
        let data = await loginApi(ruleForm.userName, ruleForm.password);
        console.log(data);
        if (data.code == "001") {
          store.state.user = data.user;
          localStorage.setItem("user", JSON.stringify(data.user));
          centerDialogVisible.value = false;
          ElMessage({
            message: "登录成功",
            type: "success",
          });
          refresh();
        } else {
        }
      } else {
        register();
      }
    } else {
      return false;
    }
  });
};

const open = (flags) => {
  flag.value = flags;
  centerDialogVisible.value = true;
};

const outlogin = () => {
  localStorage.removeItem("user");
  store.state.user = {};
  refresh();
};

const register = async () => {
  let data = await registerApi(ruleForm.userName, ruleForm.password);
  console.log(data);
  if (data.code == "004") {
    ElMessage({
      message: data.msg,
    });
  } else if (data.code == "001") {
    ElMessage({
      message: "注册成功",
      type: "success",
    });
    flag.value = 0;
  }
};
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
.top {
  display: flex;
  line-height: 40px;
  height: 40px;
  background-color: #e3e4e5;
  color: #999;
  padding: 0 50px;
}
.top_right {
  position: absolute;
  right: 5%;
}
.top_item {
  margin: 10px;
}
.top_item:hover {
  color: red;
}
.out {
  color: #dd001b;
  margin: 20px;
}
</style>